/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlCliente;
import Controlador.ControlCotizacion;
import Controlador.ControlProdServ;
import Modelo.Cliente;
import Modelo.Pedido;
import Modelo.Producto;
import Modelo.Servicio;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.EventObject;
import javax.swing.AbstractCellEditor;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SpinnerListModel;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Damian
 */
public class PnlPedidos extends javax.swing.JPanel {

    /**
     * Creates new form PnlPedidos
     */
    public ArrayList<Pedido> l;

    ControlCotizacion controlp = new ControlCotizacion();

    public PnlPedidos(ArrayList<Pedido> l) {
        initComponents();
        this.l = l;
        tablaPedidos.setModel(modelo());
        
        //tablaPedidos.setCellEditor(new SpinnerEditor(new String[]{"1","2"}));
    }

    public ArrayList<Pedido> getL() {
        return l;
    }

    public void setL(ArrayList<Pedido> l) {
        this.l = l;
        tablaPedidos.setModel(modelo());
    }

    public ControlCotizacion getControlp() {
        return controlp;
    }

    public void setControlp(ControlCotizacion controlp) {
        this.controlp = controlp;
    }

    public JButton getBtnSelProd() {
        return btnSelProd;
    }

    public void setBtnSelProd(JButton btnSelProd) {
        this.btnSelProd = btnSelProd;
    }

    public JButton getBtnSelServ() {
        return btnSelServ;
    }

    public void setBtnSelServ(JButton btnSelServ) {
        this.btnSelServ = btnSelServ;
    }

    public JTable getTablaPedidos() {
        return tablaPedidos;
    }

    public void setTablaPedidos(JTable tablaPedidos) {
        this.tablaPedidos = tablaPedidos;
    }

    public JButton getBtnAgregarPedido() {
        return btnAgregarPedido;
    }

    public void setBtnAgregarPedido(JButton btnAgregarPedido) {
        this.btnAgregarPedido = btnAgregarPedido;
    }

    public JSpinner getSpnCantidad() {
        return spnCantidad;
    }

    public void setSpnCantidad(JSpinner spnCantidad) {
        this.spnCantidad = spnCantidad;
    }

    public DefaultTableModel modelo() {
        String[] columnas = {"Producto",
            "Servicio", "Cantidad"};
        DefaultTableModel tablaM = new DefaultTableModel(columnas, 0) {

            @Override
            public boolean isCellEditable(int row, int column) {
                if (column == 2) {
                    return true;
                }
                return false;

                // return false; 
            }
            

        };

        try {
            for (int i = 0; i < l.size(); i++) {
                Pedido p = l.get(i);
                tablaM.addRow(new Object[]{
                    (p.getCod_prod() != -1) ? mostrarProducto(p.getCod_prod()) : "No asignado",
                    (p.getCod_serv() != -1) ? mostrarServicio(p.getCod_serv()) : "No asignado",
                    p.getPed_cantidad()});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        tablaM.addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType()==e.UPDATE) {
                    int row = tablaPedidos.getSelectedRow();
                    l.get(row).setPed_cantidad(
                            Integer.parseInt(((DefaultTableModel)tablaPedidos.getModel()).getValueAt(row, 2).toString()));
                }
            }
        });
        return tablaM;
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tablaPedidos = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        btnSelProd = new javax.swing.JButton();
        btnSelServ = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        spnCantidad = new javax.swing.JSpinner();
        btnAgregarPedido = new javax.swing.JButton();
        btnRemoverPedido = new javax.swing.JButton();
        jXStatusBar1 = new org.jdesktop.swingx.JXStatusBar();
        lblAyuda = new org.jdesktop.swingx.JXLabel();

        setLayout(new java.awt.BorderLayout());

        tablaPedidos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Pedido", "Producto", "Servicio", "Cantidad"
            }
        ));
        jScrollPane1.setViewportView(tablaPedidos);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

        btnSelProd.setText("Agregar Producto");
        btnSelProd.setToolTipText("Agregar un producto al pedido seleccionado");

        btnSelServ.setText("Agregar Servicio");
        btnSelServ.setToolTipText("Agregar un servicio al pedido seleccionado");

        jLabel1.setText("Cantidad:");

        spnCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));

        btnAgregarPedido.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-add.png"))); // NOI18N
        btnAgregarPedido.setText("Agregar Pedido");
        btnAgregarPedido.setToolTipText("Agregar un pedido");
        btnAgregarPedido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarPedidoActionPerformed(evt);
            }
        });

        btnRemoverPedido.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-remove.png"))); // NOI18N
        btnRemoverPedido.setText("Remover Pedido");
        btnRemoverPedido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverPedidoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnRemoverPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(56, 56, 56)
                        .addComponent(spnCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(btnSelServ, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnAgregarPedido, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)
                        .addComponent(btnSelProd, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(spnCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnAgregarPedido)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnRemoverPedido)
                .addGap(15, 15, 15)
                .addComponent(btnSelProd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSelServ)
                .addContainerGap(232, Short.MAX_VALUE))
        );

        add(jPanel1, java.awt.BorderLayout.EAST);

        lblAyuda.setForeground(new java.awt.Color(204, 102, 0));
        lblAyuda.setText("Puede cambiar la cantidad de los pedidos directamente en la tabla.");
        jXStatusBar1.add(lblAyuda);

        add(jXStatusBar1, java.awt.BorderLayout.PAGE_END);
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarPedidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarPedidoActionPerformed
        l.add(new Pedido(-1, -1, -1, -1, Integer.parseInt(spnCantidad.getValue().toString())));
        tablaPedidos.setModel(modelo());
    }//GEN-LAST:event_btnAgregarPedidoActionPerformed

    private void btnRemoverPedidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverPedidoActionPerformed
        int i = tablaPedidos.getSelectedRow();

        if (i >= 0) {
            l.remove(i);
            tablaPedidos.setModel(modelo());
        } else {
            JOptionPane.showMessageDialog(this, "Seleccione un pedido para eliminar.");
        }
    }//GEN-LAST:event_btnRemoverPedidoActionPerformed

    public String mostrarProducto(Integer cod) {
        String r = "";
        ArrayList<Producto> listProd = new ControlProdServ().listarProductos();
        for (int i = 0; i < listProd.size(); i++) {
            Producto producto = listProd.get(i);
            if (producto.getCodigo().equals(cod.toString())) {
                r = cod.toString() + " - " + producto.getNombre();
                break;
            }
        }
        return r;
    }

    public String mostrarServicio(Integer cod) {
        String r = "";
        ArrayList<Servicio> listServ = new ControlProdServ().listarServicios();
        for (int i = 0; i < listServ.size(); i++) {
            Servicio serv = listServ.get(i);
            if (serv.getCodigo().equals(cod.toString())) {
                r = cod.toString() + " - " + serv.getNombre();
                break;
            }
        }
        return r;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarPedido;
    private javax.swing.JButton btnRemoverPedido;
    private javax.swing.JButton btnSelProd;
    private javax.swing.JButton btnSelServ;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXStatusBar jXStatusBar1;
    private org.jdesktop.swingx.JXLabel lblAyuda;
    private javax.swing.JSpinner spnCantidad;
    private javax.swing.JTable tablaPedidos;
    // End of variables declaration//GEN-END:variables
}
